package com.goldsprite.gameframeworks.ecs.component;

import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.utils.Pool;
import com.badlogic.gdx.graphics.*;
import com.goldsprite.gameframeworks.ecs.SpriteUtils;
import com.goldsprite.gameframeworks.ecs.system.*;
import com.badlogic.gdx.graphics.glutils.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.goldsprite.gameframeworks.assets.*;
import com.goldsprite.gameframeworks.utils.math.Vector2;

import java.util.ArrayList;
import java.util.List;

public class WorldCloudComponent extends SpriteComponent {
	private OrthographicCamera cam, cloudCam;
	private float layerWidth, layerHeight;

	private GameRes res = GameRes.Clouds;
	private float regionWidth = res.getUVUnit()[0], regionHeight = res.getUVUnit()[1];
	private Array<TextureRegion> cloudRegions;

	private Vector2 followPoint = new Vector2();

	// 云朵对象池和活跃列表
	private Pool<Cloud> cloudPool;
	private List<Cloud> activeClouds;

	// 云朵参数
	private float velRate = 2f;
	private float minSpeed = 20f * velRate;
	private float maxSpeed = 50f * velRate;
	private float spawnInterval = 0.3f;
	private float spawnTimer = 0f;
	private int maxClouds = 128, startCount = maxClouds;
	private float heightArea = 0.3f, cwidth = 2.4f, high = /*0.65f*/1.2f;
	private Vector2 diffVec2 = new Vector2();

	// 云朵类型定义
	private static final int CLOUD_TYPE_LARGE = 0;  // 大云 (0-3)
	private static final int CLOUD_TYPE_MEDIUM = 1; // 中云 (4-7)
	private static final int CLOUD_TYPE_SMALL = 2;  // 小云 (8-9)

	// 云朵类型概率权重 (小云>中云>大云)
	private final float[] cloudTypeWeights = {1.0f, 2.0f, 3.0f}; // 大云:1, 中云:2, 小云:3

	// 云朵内部类
	private static class Cloud {
		TextureRegion region;
		float x, y;
		float speed;
		float width, height;
		boolean active;

		public void set(TextureRegion region, float x, float y, float speed, float width, float height) {
			this.region = region;
			this.x = x;
			this.y = y;
			this.speed = speed;
			this.width = width;
			this.height = height;
			this.active = true;
		}
	}

	@Override
	public void awake() {
		super.awake();
		cam = GameSystem.worldCamera;
		layerWidth = cam.viewportWidth * cwidth;
		layerHeight = cam.viewportHeight * heightArea;

		diffVec2.set(cam.viewportWidth/2f, cam.viewportHeight * high);
		getTransform().getPosition().set(diffVec2);

		cloudCam = new OrthographicCamera();
		cloudCam.setToOrtho(true, layerWidth, layerHeight);
		cloudCam.update();

		SpriteUtils.setUVUnit(GameRes.Clouds.getUVUnit());
		cloudRegions = SpriteUtils.splitAllFrames(GameRes.Clouds, 4, 3, 10);

		// 初始化对象池和活跃列表
		cloudPool = new Pool<Cloud>() {
			@Override
			protected Cloud newObject() {
				return new Cloud();
			}
		};
		activeClouds = new ArrayList<>();

		// 开局生成一排云朵
		float totalDelta = startCount * spawnInterval, delta = 1/60f;
		while(totalDelta > 0) {
			updateClouds(delta);
			totalDelta -= delta;
		}
	}

	/**
	 * 根据概率权重随机选择云朵类型
	 */
	private int getRandomCloudType() {
		float totalWeight = 0;
		for (float weight : cloudTypeWeights) {
			totalWeight += weight;
		}

		float randomValue = (float) Math.random() * totalWeight;
		float currentWeight = 0;

		for (int i = 0; i < cloudTypeWeights.length; i++) {
			currentWeight += cloudTypeWeights[i];
			if (randomValue <= currentWeight) {
				return i;
			}
		}

		return CLOUD_TYPE_SMALL; // 默认返回小云
	}

	/**
	 * 根据云朵类型获取随机纹理区域
	 */
	private TextureRegion getRandomRegionByType(int cloudType) {
		switch (cloudType) {
			case CLOUD_TYPE_LARGE:
				// 大云: 索引 0-3
				return cloudRegions.get((int) (Math.random() * 4));
			case CLOUD_TYPE_MEDIUM:
				// 中云: 索引 4-7
				return cloudRegions.get(4 + (int) (Math.random() * 4));
			case CLOUD_TYPE_SMALL:
				// 小云: 索引 8-9
				return cloudRegions.get(8 + (int) (Math.random() * 2));
			default:
				return cloudRegions.random();
		}
	}

	@Override
	public void update(float delta) {
		super.update(delta);

		updateClouds(delta);
	}

	Vector2 originalPos = new Vector2();
	@Override
	public void render(Batch batch, float delta) {
		// 保存当前transform状态
		originalPos.set(getTransPos());
		float oriScl = getTransform().getScale().x;
		TextureRegion originalRegion = getRegion();

		// 渲染所有活跃云朵（相对于组件位置）
		Vector2 componentPos = getTransPos();
		for (Cloud cloud : activeClouds) {
			if (cloud.active) {
				// 设置云朵相对于组件的位置
				getTransform().getPosition().set(
					cloud.x,
					cloud.y + cam.viewportHeight * high + (cam.position.y-cam.viewportHeight * high) * 0.3f
				);
				setRegion(cloud.region);
				getTransform().getScale().set(cloud.width / regionWidth, cloud.height / regionHeight);
				super.render(batch, delta);
			}
		}

		// 恢复原始状态
		getTransform().getPosition().set(originalPos);
		setRegion(originalRegion);
		getTransform().setScale(oriScl);
	}

	private void updateClouds(float delta) {
		// 更新存活云朵位置
		for (int i = activeClouds.size() - 1; i >= 0; i--) {
			Cloud cloud = activeClouds.get(i);
			cloud.x -= cloud.speed * delta;

			// 移除移出屏幕的云朵
			if (cloud.x < 0) {
				activeClouds.remove(i);
				cloudPool.free(cloud);
			}
		}

		// 生成新云朵
		spawnTimer += delta;
		if (spawnTimer >= spawnInterval && activeClouds.size() < maxClouds) {
			spawnCloud();
			spawnTimer = 0f;
		}
	}

	private Vector2 getTransPos() {
		return fields.transform.getPosition();
	}

	private void spawnCloud() {
		Cloud cloud = cloudPool.obtain();

		// 根据概率选择云朵类型
		int cloudType = getRandomCloudType();
		TextureRegion region = getRandomRegionByType(cloudType);

		// 根据类型设置参数
		float scale = 1;
		float width = regionWidth * scale;
		float height = regionHeight * scale;
		float speed = minSpeed + (float) Math.random() * (maxSpeed - minSpeed);
		float y = (float) Math.random() * (layerHeight - height);

		// 从右侧生成
		float ran = (float)Math.random()*150;
		float x = layerWidth-width - ran;

		cloud.set(region, x, y, speed, width, height);
		activeClouds.add(cloud);
	}
}
